﻿using Base.Entities.Model;
using Base.ModuleBase;
using SignalRClientTool.Models;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRClientTool.ViewModels
{
    public class NetConfigViewModel : DialogViewModelBase
    {
        private readonly IClientToolManager _clientToolManager;

        public NetConfigViewModel(IClientToolManager clientToolManager)
        {
            _clientToolManager = clientToolManager;
        }

        public ObservableCollection<CommonModel> ConfigInfos { get; set; } = new ObservableCollection<CommonModel>();

        private DelegateCommand _SaveCommand;
        public DelegateCommand SaveCommand => _SaveCommand ?? (_SaveCommand = new DelegateCommand(OnSaveCommand));

        private async void OnSaveCommand()
        {
            var tempInfos = new Dictionary<string, object>();
            foreach (var item in ConfigInfos)
            {
                tempInfos.Add(item.Name, item.Value);
            }
            await _clientToolManager.SaveMqttConfig(tempInfos);
            _logger.Debug($"保存Mqtt配置 {JsonHelper.Serialize(tempInfos)}");
            MessageHelper.ShowTips("保存成功");
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            GetMqttConfig();
            base.OnDialogOpened(parameters);
        }

        private void GetMqttConfig()
        {
            ConfigInfos.Clear();
            var tempInfos = _clientToolManager.GetNetConfigToDictionary();
            foreach (var item in tempInfos)
            {
                ConfigInfos.Add(new CommonModel()
                {
                    Name = item.Key,
                    Value = item.Value
                });
            }
        }
    }
}
